package com.moore.Servlet;

import com.alibaba.fastjson2.JSON;
import com.moore.net.HttpRequest;
import com.moore.net.HttpResponse;
import com.moore.net.HttpServlet;
import com.moore.utils.CommentUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class CommentServlet extends HttpServlet {
    @Override
    public byte[] doGet(HttpRequest request, HttpResponse response) {
        String responseData;
        String type = request.getParams().get("type");
        if (type.equals("add")) {
            String goodsId = request.getParams().get("goodsId");
            String nickname;
            try {
                nickname = URLDecoder.decode(request.getParams().get("nickname"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            String content;
            try {
                content = URLDecoder.decode(request.getParams().get("content"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            responseData = CommentUtils.insertComment(goodsId,nickname,content);
        } else if (type.equals("list")) {
            String goodsId = request.getParams().get("goodsId");
            responseData = JSON.toJSONString(CommentUtils.getComment(goodsId));
        } else {
            responseData = "error";
        }
        return responseData.getBytes();
    }
}
